import { modelType } from '@/types/model'
import { AxiosResponse } from 'axios'
import * as XLSX from 'xlsx'

export async function readFromXlsx(callBack: (wb: XLSX.WorkBook) => {}) {
  const files = await showOpenFilePicker()
  const file = await files[0].getFile()

  const reader = new FileReader()
  reader.onload = async function (e: any) {
    const data = e.target.result
    const wb = XLSX.read(data, { type: 'binary' })
    callBack(wb)
  }
  reader.readAsBinaryString(file)
}

export async function addModels<T extends modelType>(
  wb: XLSX.WorkBook,
  sectionId: number,
  sheetName: string,
  model: T,
  add: (data: any) => Promise<AxiosResponse<T, any>>,
) {
  const ws = wb.Sheets[sheetName]
  const row = XLSX.utils.sheet_to_json(ws)

  for (const r of row) {
    const keys = Reflect.ownKeys(model)
    for (const key of keys) {
      const value = Reflect.get(r as any, key) || ''

      if (typeof Reflect.get(model, key) === 'string') {
        Reflect.set(model, key, value.toString())
      } else {
        Reflect.set(model, key, value)
      }
    }
    await add({ ...model, sectionId })
  }
}
